package main

import (
	"flag"
	"fmt"
	"net/http"
	"strings"

	"github.com/blog-zero/common/cors"

	"github.com/blog-zero/api/admin/internal/common/errorx"
	"github.com/blog-zero/api/admin/internal/config"
	"github.com/blog-zero/api/admin/internal/handler"
	"github.com/blog-zero/api/admin/internal/svc"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
)

var configFile = flag.String("f", "etc/admin-api.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(cors.MiddlewareHandler, cors.NotAllowedHandler),
		rest.WithUnauthorizedCallback(func(w http.ResponseWriter, r *http.Request, err error) {
			if strings.Contains(err.Error(), "Token is expired") {
				httpx.WriteJson(w, http.StatusUnauthorized, errorx.NewTokenExpire(err.Error()))
			}
		}))
	defer server.Stop()

	ctx := svc.NewServiceContext(c)

	server.Use(ctx.AddLog)

	handler.RegisterHandlers(server, ctx)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
